﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerTankFind : MonoBehaviour
{

    public bool isRun;//是否运行
    private GameObject targetObj;//当前目标
    private bool isOnlyOne = false;
    private void Update()
    {
        if (isRun)
        {
            if(!isOnlyOne)
            {
                StartCoroutine(WaitForSecondsToDo(0.1f));//只运行一次
                //print("开启水平旋转开关");
                isOnlyOne = true;
            }

            if (targetObj == null)
                return;
            //计算方向
            Vector3 direction = targetObj.transform.position - transform.position;
            transform.rotation = Quaternion.Slerp(transform.rotation,
                Quaternion.LookRotation(direction),
                0.01f
                );

        }
        else
        {
            if (isOnlyOne)
            {
                StopAllCoroutines();//重复关闭
                //print("关闭水平旋转开关");
                isOnlyOne = false;
            }
        }
    }

    //协程
    IEnumerator WaitForSecondsToDo(float t)
    {
        while (true)
        {
            yield return new WaitForSeconds(t);
            targetObj = FindClosestObject("Enemy");
        }
    }
    //返回最近物体
    GameObject FindClosestObject(string tag)
    {
        //Todo 1.定义数组
        GameObject[] enemyArr;//敌人数组
        //Todo 2.通过标签查找所有敌人
        enemyArr = GameObject.FindGameObjectsWithTag(tag);
        //Todo 3.定义一个保存最近敌人的变量
        GameObject closestObj = null;//最近物体
        //Todo 4.距离变量，无穷大
        float distance = Mathf.Infinity;//无穷大
        //Todo 5.遍历列表
        foreach (GameObject obj in enemyArr)
        {
            //Todo 6.计算向量的平方长度
            Vector3 offset = obj.transform.position - transform.position;
            float sqrLen = offset.sqrMagnitude;//平方长度
            //Todo 7.比较距离
            if (sqrLen < distance)
            {
                closestObj = obj;
                distance = sqrLen;
            }
        }
        return closestObj;
    }
}
